import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import QueueView from '../views/Queue.vue'
import ConsumerView from '../views/Consumer.vue'
import MessageView from '../views/Message.vue'
import LoginView from '../views/Login.vue' // 新增登录页面
import { ElMessage } from 'element-plus'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
            redirect: '/queue',
            children: [
                {
                    path: '/queue',
                    name: 'Queue',
                    component: QueueView,
                    meta: { requiresAuth: true } // 需要认证
                },
                {
                    path: '/consumer',
                    name: 'Consumer',
                    component: ConsumerView,
                    meta: { requiresAuth: true }
                },
                {
                    path: '/message',
                    name: 'Message',
                    component: MessageView,
                    meta: { requiresAuth: true }
                }
            ]
        },
        {
            path: '/login',
            name: 'Login',
            component: LoginView,
            meta: { guestOnly: true } // 仅限访客访问
        },
        // {
        //     path: '/:pathMatch(.*)*',
        //     name: 'NotFound',
        //     component: NotFoundView
        // }
    ],
})


router.beforeEach(async (to, from, next) => {
    // 判断是否需要认证
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
    const isLoginPage = to.name === 'Login'
    // 直接从localStorage获取token（移除后端验证）
    const token = localStorage.getItem('token')

    // 简化判断逻辑，避免异步操作导致的循环
    if (requiresAuth && !token) {
        // 需要认证但没有token
        next({ name: 'Login', query: { redirect: to.fullPath } })
        ElMessage.warning('请先登录')
    } else if (isLoginPage && token) {
        // 已登录状态访问登录页，重定向到首页
        next({ name: 'home' })
    } else {
        // 正常访问
        next()
    }
})

export default router
